<template>
  <div>
    <a-table
      class="a-table"
      :row-key="rowKey"
      :columns="cols"
      :data-source="tableData"
      :loading="loading"
      :pagination="pagination"
      :row-selection="
        showCheckbox ? { selectedRowKeys, onChange: onRowSelectChange } : null
      "
      @change="handleTableChange"
    >
      <template v-for="(fn, slotKey) of $slots" #[slotKey]="scope">
        <slot :name="slotKey" v-bind="scope" />
      </template>
    </a-table>
  </div>
</template>

<script>
import { reactive, ref } from "vue";
import { $me } from "~mixins/useMsg";
export default {
  emits: ["update:selectedKeys"],
  props: {
    rowKey: {
      type: String,
      default: "id",
    },
    showCheckbox: {
      type: Boolean,
      default: true,
    },
    cols: {
      type: Array,
      required: true,
    },
    load: {
      type: Function,
      required: true,
    },
  },
  setup(props, { emit }) {
    let loading = ref(false);
    let tableData = ref([]);
    let pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showTotal(total) {
        return `共有${total}条数据`;
      },
      hideOnSinglePage: true,
      pageSizeOptions: ["10", "20", "30", "40", "50"],
    });
    let selectedRowKeys = ref([]);

    /**
     * 重新加载表格，回到第一页
     */
    let refresh = () => {
      pagination.current = 1;
      selectedRowKeys.value = [];
      loadData();
    };

    let loadData = async () => {
      try {
        loading.value = true;
        let {
          success,
          data: { list, total },
        } = await props.load({
          pageIndex: pagination.current,
          pageSize: pagination.pageSize,
        });

        if (success) {
          //判断实际的总页数小于当前页码，则按实际的总页数为页码来查询
          let totalPage = Math.ceil(total / pagination.pageSize);
          if (totalPage < pagination.current) {
            pagination.current = totalPage;
            loadData();
          } else {
            tableData.value = list;
            pagination.total = total;
            loading.value = false;
          }
        }
      } catch (error) {
        $me("接口数据格式不正确！");
      } finally {
        loading.value = false;
      }
    };

    let onRowSelectChange = (selectedKeys) => {
      selectedRowKeys.value = selectedKeys;
      emit("update:selectedKeys", selectedKeys);
    };

    /**
     * 表格分页或排序改变时触发数据获取
     */
    let handleTableChange = ({ current }) => {
      pagination.current = current;
      loadData();
    };

    function onShowSizeChange(i, pageSize) {
      pageSize.value = pageSize;
      refresh();
    }

    loadData();

    return {
      loading,
      handleTableChange,
      pagination,
      tableData,
      refresh,
      onShowSizeChange,
      selectedRowKeys,
      onRowSelectChange,
      loadData,
    };
  },
};
</script>

<style scoped lang='scss'>
</style>